package org.filetransfer.file_transfer_java_backend.service;
import org.filetransfer.file_transfer_java_backend.entity.DailyStat;
import org.filetransfer.file_transfer_java_backend.repository.DailyStatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
@Service
public class StatService {

    @Autowired
    private DailyStatRepository dailyStatRepository;

    @Transactional
    public void recordTodayStat(String type) {
        LocalDate today = LocalDate.now();
        Optional<DailyStat> statOpt = dailyStatRepository.findByStatDateAndType(today, type);

        if (statOpt.isPresent()) {
            DailyStat stat = statOpt.get();
            stat.setCount(stat.getCount() + 1);
            dailyStatRepository.save(stat);
        } else {
            DailyStat newStat = new DailyStat();
            newStat.setStatDate(today);
            newStat.setType(type);
            newStat.setCount(1L);
            dailyStatRepository.save(newStat);
        }
    }

    public long getTodayCount(String type) {
        return dailyStatRepository
                .findByStatDateAndType(LocalDate.now(), type)
                .map(DailyStat::getCount)
                .orElse(0L);
    }

    public long getTotalCount(String type) {
        return dailyStatRepository.findAll().stream()
                .filter(stat -> stat.getType().equals(type))
                .mapToLong(DailyStat::getCount)
                .sum();
    }
    public Map<String, Map<String, Long>> getAllStats() {
        Map<String, Map<String, Long>> result = new HashMap<>();
        List<String> types = List.of("upload", "download", "visit");

        for (String type : types) {
            long today = getTodayCount(type);
            long total = getTotalCount(type);
            result.put(type, Map.of("today", today, "total", total));
        }
        return result;
    }
    public Map<LocalDate, Long> getStatsInRange(String type, LocalDate start, LocalDate end) {
        List<DailyStat> list = dailyStatRepository.findByTypeAndStatDateBetween(type, start, end);

        Map<LocalDate, Long> result = new LinkedHashMap<>();
        LocalDate date = start;
        while (!date.isAfter(end)) {
            result.put(date, 0L);
            date = date.plusDays(1);
        }

        for (DailyStat stat : list) {
            result.put(stat.getStatDate(), stat.getCount());
        }

        return result;
    }

}

